`
https://leetcode.cn/problems/balance-a-binary-search-tree/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var balanceBST = function (root) {
  // 虽然可以用红黑树的旋转方式实现平衡，但难度较大
  // 可以通过中序排序获取到有序数组
  // 然后套用将有序数组转换为二叉搜索树的逻辑
  // https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/

  const arr = [];
  (function traverse(root) {
    if (root === null) return
    traverse(root.left)
    arr.push(root.val)
    traverse(root.right)
  })(root)

  const build = (nums, left, right) => {
    if (left > right) {
      return null
    }

    const mid = Math.floor((left + right) / 2)
    const root = new TreeNode(nums[mid])
    root.left = build(nums, left, mid - 1)
    root.right = build(nums, mid + 1, right)

    return root
  }

  return build(arr, 0, arr.length - 1)
};